<?php

namespace App\Admin\Models;

use App\Admin\Models\BaseModel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Encore\Admin\Facades\Admin;
use App\Services\Common;
use App\Services\Store;

class Income extends BaseModel
{
    //指定主键
    protected $primaryKey = 'day';

    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);

		///////获取数据//////////////////////////////////////////////////////////////////////////////////////
		$sId = Admin::user()->sId;

		$Common = new Common();
    	$list = $Common->getStoreStatsList($sId, 'income', $page, $perPage);
    	//print_r(json_encode($list));exit;
    	$list = json_decode(json_encode($list), true);

		////////获取数据/////////////////////////////////////////////////////////////////////////////////////

		$total = count($list);

        extract($list);

        $tags = static::hydrate($list);

        $paginator = new LengthAwarePaginator($tags, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    /**
     * Add a basic where clause to the query.
     *
     * @param  string|array|\Closure  $column
     * @param  mixed   $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and'){
    	// http://localhost:96/admin/remark/remarkTag?rtcId=1
    	// $column rtcId
    	// $operator 1
    	// $value null
    	// $boolean and
    	return $this;
    }

    // 获取单项数据展示在form中
	public function findOrFail($id)
	{
		$sId = Admin::user()->sId;
		$url = $this->host."/member/get/{$id}?mcKey=".$sId;
		$response = Curl::to($url)->get();
		$data = $this->handelApiData($response);

	    return static::newFromBuilder($data);
	}

	// 保存提交的form数据
	public function save(array $options = Array())
	{
	    $attributes = $this->getAttributes();

		$sId = Admin::user()->sId;
	    $userName = Admin::user()->name;
	    $now = date('Y-m-d H:i:s', time());

	    if (isset($_POST['chargeMoney'])){
	    	$walletUrl = $this->host."/wallet/addTrade";
			$walletData = array();
			$walletData['wcusKey'] = $sId;
			$walletData['wtObj'] = 'member';
			$walletData['wtObjId'] = $attributes['muCode'];
			$walletData['createUser'] = $userName;
			$walletData['uId'] = $attributes['muCode'];
			$walletData['wtChangedMoney'] = $_POST['chargeMoney'];
			$walletData['wtAbstract'] = '会员充值';
//			$walletData['wcObj'] = 'recharge';
			$rst = Curl::to($walletUrl)->withData($walletData)->post();
			$rst = json_decode($rst, true);
			if($rst['code'] == 1){// 添加日记录
			    $store = DB::table('store')->where('sId', $sId)->first();
			    if($store){
                    $day['scKey'] = $sId;
                    $day['sdObjId'] = $store->sCode;
                    $day['sdName'] = 'recharge';
                    $day['sdValue'] = $walletData['wtChangedMoney'];
                    $url = $this->host."/statistics/dayAdd";
                    $rst = Curl::to($url)->withData($day)->post();
					
					$day['sdName'] = 'rechargeNum';
                    $day['sdValue'] = 1;
                    $rst = Curl::to($url)->withData($day)->post();
               }
            }

			$sInfo = DB::table('store')->where('sId', $sId)->first();
			// 单独记录会员充值
			DB::Table('member_users')->where('muCode', $attributes['muCode'])->increment('muAccount', $_POST['chargeMoney']);

			// 增加店铺流水
			$Store = new Store();
			$Store->addWalletTrade($sId, 'member', $attributes['muCode'], '会员卡充值', $userName,
									$sInfo->sCode, $_POST['chargeMoney'], $wtMemo='', 0, $_POST['chargeMoney']);

			$Store->addStatsDay($sId, $sInfo->sCode, 'flowAccount', $_POST['chargeMoney'], '');
			$Store->addStatsDay($sId, $sInfo->sCode, 'profit', $_POST['chargeMoney'], '');
	    	return $this;
	    }


	    // 根据是否有id判断添加还是更新
	    if (isset($attributes['muId']) && !empty($attributes['muId'])){
	    	$ignore = ['mcId', 'muAccount', 'muPoints', 'muReferrerName',
	    		'muReferrerId', 'muTotalExpend', 'createUser',
	    		'createTime', 'updateUser', 'updateTime'];
		    $newAttributes = array();
		    foreach($attributes as $key => $value){
		    	if (!in_array($key, $ignore)){
		    		$newAttributes[$key] = $value;
		    	}
		    }

		    $newAttributes['updateUser'] = $userName;
		    //print_r($newAttributes);exit;
		    // save $attributes
			$url = $this->host."/member/edit";
	    }else{
	    	$ignore = ['mcId', 'muAccount', 'muPoints', 'muTotalExpend',
	    	'createUser', 'createTime', 'updateUser', 'updateTime'];
		    $newAttributes = array();
		    foreach($attributes as $key => $value){
		    	if (!in_array($key, $ignore)){
		    		$newAttributes[$key] = $value;
		    	}
		    }

		    $newAttributes['createUser'] = $userName;
		    $newAttributes['muRealName'] = $newAttributes['muNickName'];
		    //print_r($newAttributes);exit;
		    // save $attributes
			$url = $this->host."/member/add";

	    }

	    $newAttributes['mcKey'] = $sId;

		$response = Curl::to($url)
					->withData($newAttributes)
					->post();

		$data = json_decode($response, true);
		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);

		    return back()->with(compact('success'));
		}
		if ($data['code'] == 0){
			// 抛出错误信息
			$error = new MessageBag([
		        'title'   => '保存失败',
		        'message' => $data['msg'],
		    ]);

		    return back()->with(compact('error'));
		}

		if (!isset($attributes['muId'])){
			$Common = new Common();
			$Common->addStats($sId, 'newMember', 1, $Common->getScode($sId));
		}

		return $this;
	}

	// 重写此方法，因为删除前要调用。不写则报错
	public function find($id){
		$this->muId = $id;
		return $this;
	}

	// 重写删除方法
	public function delete(){

		$attributes = $this->getAttributes();

		$remarkKey = config('services.extend.remarkKey');
		$remarkHost = config('services.extend.remarkHost');
		$url = $remarkHost.'/api/remark/delTag';

		// 请求外部数据
		$Functions = new Functions();
		$attributes['rcKey'] = $remarkKey;

		$data = $Functions->Post($url, $attributes);
		$data = json_decode($data, true);
		if (!isset($data['code'])){
			$error = new MessageBag([
		        'title'   => '系统错误',
		        'message' => '',
		    ]);

		    return back()->with(compact('success'));
		}
		if ($data['code'] == 0){
			// 抛出错误信息
			$this->saving(function ($form) {

			    $error = new MessageBag([
			        'title'   => '保存失败',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('error'));
			});
		}else{
			// 抛出错误信息
			$this->saving(function ($form) {

			    $error = new MessageBag([
			        'title'   => '保存成功',
			        'message' => $data['msg'],
			    ]);

			    return back()->with(compact('success'));
			});
		}

		return $this;
	}

//	// 设置logo_url属性重写  提交信息时进入此方法
//	public function setLogoUrlAttribute($pictures)
//	{
////	    if (is_array($pictures)) {
////	        $this->attributes['pictures'] = json_encode($pictures);
////	    }
//	}
//
//	// 获取logo_url属性重写 获取信息时进入此方法
//	public function getLogoUrlAttribute($pictures)
//	{
//		if (is_array($pictures)){
//			return $pictures;
//		}
//	    return json_decode($pictures, true);
//	}
}
